﻿using System.Linq.Expressions;
using AutoMapper;
using CozeDomain.Entities;
using CozeDomain.IRepositories;
using CozeDomain.IServices;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.JwtUtil;
using D.UtilFreesqlOrm;
using Microsoft.AspNetCore.Http;
using D.Util.UtilNLog;
using CozeDto.TenantsDtos;
using CozeDto.ProjectDtos;
using System.Web;

namespace CozeDomain.Services
{
    /// <summary>
    /// 管理员业务实现
    /// </summary>
    public class TenantsService : BaseService<TenantsEntity>, ITenantsService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly IJwtService _tokenService;
        private readonly INLogService _nlogService;
        private readonly ITenantsEntityRepository _repository;
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 构造注入
        /// </summary>
        public TenantsService(IMapper mapper, ICacheService cache, IJwtService tokenService, INLogService nlogService, IHttpContextAccessor httpContextAccessor,
            ITenantsEntityRepository repository)
        {
            // 用于base方法
            base._baseDal = repository;
            this._repository = repository;
            _cache = cache;
            _mapper = mapper;
            _nlogService = nlogService;
            _tokenService = tokenService;
            _httpContextAccessor = httpContextAccessor;
        }

        #region 增删改查

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddTenantsAsync(ReqAddTenants reqModel)
        {
            var exists = await _repository.GetModelAsync(m => m.Name == reqModel.Name || m.RealmName == reqModel.RealmName);
            if (exists != null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, Msg = "站点名称或域名已存在" };
            }

            var insertEntity = _mapper.Map<ReqAddTenants, TenantsEntity>(reqModel);
            insertEntity.DeleteFlag = false;
            insertEntity.CreateTime = DateTime.Now;
            insertEntity.Id = D.UtilFreesqlOrm.FreesqlOrm.NewId;
            insertEntity.Status = true;

            var dbres = await _repository.AddAsync(insertEntity);

            return dbres.NormalResponse();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteTenantsAsync(List<string> ids)
        {
            var dbres = await _repository.DeleteAsync(m => ids.Contains(m.Id));
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> UpdateTenantsAsync(ReqUpdateTenants reqModel)
        {
            var updateEntity = await _repository.GetModelAsync(m => m.Id == reqModel.Id);
            if (updateEntity == null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, Msg = "该信息不存在" };
            }

            var exists = await _repository.GetModelAsync(m => (m.Name == reqModel.Name || m.RealmName == reqModel.RealmName) && updateEntity.Id != m.Id);
            if (exists != null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, Msg = "站点名称或域名已存在" };
            }

            updateEntity.Name = reqModel.Name;
            updateEntity.RealmName = updateEntity.RealmName;
            updateEntity.Status = reqModel.Status;
            updateEntity.UpdateTime = DateTime.Now;
            updateEntity.UpdateUser = reqModel.UpdateUser;
            updateEntity.Description = reqModel.Description;

            var dbres = await _repository.UpdateAsync(updateEntity);

            return dbres.NormalResponse();
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepTenantsInfo>> GetTenantsAsync(string id)
        {
            var dbres = await _repository.GetModelAsync(m => m.Id == id);
            var res = _mapper.Map<TenantsEntity, RepTenantsInfo>(dbres);
            return res.GetResponse();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<RepTenantsInfo>>> QueryTenantsListAsync()
        {
            var dbres = await _repository.GetListAsync(m => m.Status.Value);
            var res = _mapper.Map<List<TenantsEntity>, List<RepTenantsInfo>>(dbres);
            return res.GetResponse();
        }

        /// <summary>
        /// 获取分页
        /// </summary>
        /// <param name="reqQueryTenantsPage"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageModel<RepTenantsInfo>>> QueryTenantsPagesAsync(ReqQueryTenantsPage reqQueryTenantsPage)
        {
            Expression<Func<TenantsEntity, bool>> where = null;


            if (reqQueryTenantsPage.Status != null)
            {
                where = where.And(m => m.Status == reqQueryTenantsPage.Status);
            }

            if (!string.IsNullOrEmpty(reqQueryTenantsPage.Name))
            {
                where = where.And(m => m.Name.Contains(reqQueryTenantsPage.Name));
            }

            if (!string.IsNullOrEmpty(reqQueryTenantsPage.RealmName))
            {
                where = where.And(m => m.RealmName.Contains(reqQueryTenantsPage.RealmName));
            }

            var dbres = await _repository.GetPagesAsync(reqQueryTenantsPage.PageSize, reqQueryTenantsPage.PageNo, where, m => m.CreateTime);

            var resData = _mapper.Map<List<TenantsEntity>, List<RepTenantsInfo>>(dbres.Data);
            PageModel<RepTenantsInfo>? res = new PageModel<RepTenantsInfo>()
            {
                PageNo = dbres.PageNo,
                PageSize = dbres.PageSize,
                TotalCount = dbres.TotalCount,
                TotalPage = dbres.TotalPage,
                Data = resData
            };

            return res.GetResponse();
        }


        /// <summary>
        /// 获取站点详情
        /// </summary>
        /// <param name="realmName"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepNoticeDetail>> GetTenantsNoticeAsync(string realmName)
        {
            var dbres = await _repository.GetModelAsync(m => m.RealmName == HttpUtility.UrlDecode(realmName));
            var res = new RepNoticeDetail() { Count = dbres != null ? 1 : 0, Detail = dbres?.Notice };
            return res.GetResponse();
        }
        #endregion
    }
}